package com.example.teacherservice.service;

import com.example.teacherservice.dto.ClassCourseDTO;
import com.example.teacherservice.dto.ClassInfo;
import com.example.teacherservice.dto.StudentClassDTO;
import com.example.teacherservice.dto.StudentClassInfo;
import com.example.teacherservice.entity.*;
import com.example.teacherservice.exception.ResourceNotFoundException;
import com.example.teacherservice.repository.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class StudentClassService {

    private final StuClassRepository stuClassRepository;
    private final ClassRepository classRepository;
    private final CouClassRepository couClassRepository;
    private final CourseRepository courseRepository;
    private final StudentRepository studentRepository;
    private final StuCourseRepository stuCourseRepository;

    @Autowired
    public StudentClassService(StuClassRepository stuClassRepository,
                               ClassRepository classRepository,
                               CouClassRepository couClassRepository,
                               CourseRepository courseRepository,
                               StudentRepository studentRepository,
                               StuCourseRepository stuCourseRepository) {
        this.stuClassRepository = stuClassRepository;
        this.classRepository = classRepository;
        this.couClassRepository = couClassRepository;
        this.courseRepository = courseRepository;
        this.studentRepository = studentRepository;
        this.stuCourseRepository = stuCourseRepository;
    }

    /**
     * 根据学生ID获取班级列表
     */
    public List<StudentClassInfo> getClassesByStudentId(Long studentId) {
        return stuClassRepository.findClassesByStudentId1(studentId);
    }

    /**
     * 获取班级详细信息
     */
    public StudentClassDTO getClassDetail(Long studentId, Long classId) {
        // 验证学生是否在班级中
        if (!existsByStudentIdAndClassId(studentId, classId)) {
            throw new IllegalArgumentException("学生不在该班级中");
        }

        return classRepository.findById(classId)
                .map(c -> new StudentClassDTO(
                        c.getId(),
                        c.getClassName(),
                        c.getClassStuNum(),
                        c.getCreateTime()
                ))
                .orElseThrow(() -> new IllegalArgumentException("班级不存在"));
    }

    /**
     * 获取班级课程列表（优化版，使用关联实体）
     */
    public List<ClassCourseDTO> getClassCourses(Long studentId, Long classId) {
        // 验证学生是否在班级中
        if (!existsByStudentIdAndClassId(studentId, classId)) {
            throw new IllegalArgumentException("学生不在该班级中");
        }

        return couClassRepository.findByClassIdWithCourse(classId).stream()
                .map(couClass -> {
                    Course course = couClass.getCourse();
                    return new ClassCourseDTO(
                            course.getId(),
                            course.getCouName(),
                            course.getCouIntroduction(),
                            course.getCouPic(),
                            couClass.getCreateTime()
                    );
                })
                .collect(Collectors.toList());
    }

    /**
     * 检查学生是否在班级中
     */
    public boolean existsByStudentIdAndClassId(Long studentId, Long classId) {
        return stuClassRepository.existsByStuIdAndClassId(studentId, classId);
    }

    /**
     * 根据用户ID获取学生ID
     */
    public Long findStudentIdByUserId(Long userId) {
        return studentRepository.findByUserId(userId)
                .map(Student::getId)
                .orElseThrow(() -> new IllegalArgumentException("未找到该用户对应的学生信息"));
    }

    // 实现添加课程方法
    @Transactional
    public void addCourseToStudent(Long studentId, Long courseId) {
        // 验证学生存在
        if (!studentRepository.existsById(studentId)) {
            throw new ResourceNotFoundException("学生不存在");
        }

        // 验证课程存在
        if (!courseRepository.existsById(courseId)) {
            throw new ResourceNotFoundException("课程不存在");
        }

        // 检查是否已添加
        if (stuCourseRepository.existsByStudentIdAndCourseId(studentId, courseId)) {
            throw new ResourceNotFoundException("该课程已存在于您的课程表中");
        }

        // 创建关联
        StuCourse studentCourse = new StuCourse();
        studentCourse.setStuId(studentId);
        studentCourse.setCourseId(courseId);
        studentCourse.setCreateTime(LocalDateTime.now());  // 使用 now() 方法获取当前时间
        studentCourse.setUpdateTime(LocalDateTime.now()); // 使用 now() 方法获取当前时间
        stuCourseRepository.save(studentCourse);

        stuCourseRepository.save(studentCourse);
    }

    public boolean isCourseExists(Long studentId, Long courseId) {
        return stuCourseRepository.existsByStudentIdAndCourseId(studentId, courseId);
    }
}